from django.http import HttpResponseBadRequest

from login_api.models import User


def post_only(view_func):
    def _wrapped_view(request, *args, **kwargs):
        if request.method == 'POST':
            return view_func(request, *args, **kwargs)
        else:
            return HttpResponseBadRequest("Invalid request method. This view requires POST.")
    return _wrapped_view

def login_only(view_func):
    def _wrapped_view(request, *args, **kwargs):
        session = request.session
        if session.get("login"):
            return view_func(request, *args, **kwargs)
        cookies = request.COOKIES
        user_id = cookies.get("id", "")
        token = cookies.get("token", "")
        if not (user_id and token):
            return HttpResponseBadRequest("Invalid request .")
        user = User.objects.get(id=user_id)
        if user.token == token:
            session["login"] = True
            session["id"] = user_id
            return view_func(request, *args, **kwargs)
        return HttpResponseBadRequest("Invalid request .")
    return _wrapped_view

def admin_only():
    pass

def root_only():
    pass
